﻿Imports System.Data
Imports MySql.Data.MySqlClient
Public Class DManufacturers
    Dim connector As New MySqlConnection("server=127.0.0.1;database='commerce';user='root';password='';")
    Dim command As MySqlCommand
    Dim datareader As MySqlDataReader

    Private Sub DManufacturers_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        connector.Open()
        command = New MySqlCommand("select * from manufacturers", connector)
        datareader = command.ExecuteReader()
        While datareader.Read
            comID.Items.Add(datareader.Item("id"))
        End While
        datareader.Close()
        connector.Close()
    End Sub

    Private Sub comID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comID.SelectedIndexChanged
        cmdDelete.Enabled = True
        connector.Open()
        command = New MySqlCommand("select * from manufacturers where id=" & comID.Text, connector)
        datareader = command.ExecuteReader()
        While datareader.Read
            lblNameDesc.Text = datareader.Item("name")
            lblEmailDesc.Text = datareader.Item("email")
            lblTelephoneDesc.Text = datareader.Item("tel")
        End While
        datareader.Close()
        connector.Close()
    End Sub

    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        connector.Open()
        command = New MySqlCommand("select * from products where manufacturer=" & comID.Text, connector)
        datareader = command.ExecuteReader()
        Dim cont As Integer
        Dim ok As Boolean
        While datareader.Read
            cont = cont + 1
        End While
        datareader.Close()
        If cont > 0 Then
            If MessageBox.Show("There is products referenced to this manufacturer, deleting it will remove all of that products.\nReally do you want to delete it?", "Warning!", MessageBoxButtons.YesNo) = DialogResult.Yes Then
                ok = True
            Else
                ok = False
                MsgBox("Operation aborted")
            End If
        Else
            ok = True
        End If
        If ok Then
            command = New MySqlCommand("delete from manufacturers where id=" & comID.Text, connector)
            command.ExecuteNonQuery()
            MsgBox(lblNameDesc.Text & " deleted")
            comID.Items.Remove(comID.SelectedItem)
            cmdDelete.Enabled = False
            comID.Text = "Select an ID"
            lblNameDesc.Text = "-"
            lblEmailDesc.Text = "-"
            lblTelephoneDesc.Text = "-"
        End If
        connector.Close()
    End Sub
End Class